﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

using NetServ.Net.Json;

namespace _18miljard.UI.Controls
{
	public partial class TweetControl : BaseUserControl
	{
		protected override void OnFirstHit(object sender, EventArgs e)
		{
			Color[] alternateColor = new Color[2] { Color.FromArgb(192, 192, 192), Color.FromArgb(224, 224, 224) };
			
			string res = WebReader.ReadUrl("http://search.twitter.com/search.json?q=\"18 miljard\"%20OR%20bezuinigingen&rpp=100");

			JsonParser parser = new JsonParser(new StringReader(res), true);

			JsonObject obj = (JsonObject)parser.ParseObject();

			JsonArray results = (JsonArray)obj["results"];

			int colorIndex = 0;

			int count = 0;

			foreach (JsonObject o in results)
			{
				string tweet = o["text"].ToString();
				if (tweet.StartsWith("RT"))
					continue;

				count++;
				if (count >= 30)
					break;

				JsonString created =(JsonString) o["created_at"];

				DateTime dt = DateTime.Parse(created.ToString());

				string displayDate = dt.ToString("dd MMM yyyy");
				string displayTime = dt.ToString("HH:mm:ss");

				TableRow row = new TableRow();
				row.BackColor = alternateColor[colorIndex];

				TableCell cell = new TableCell();
				cell.CssClass = "tweetdate";
				cell.Text = displayDate + "<br />" + displayTime;
				row.Cells.Add(cell);

				TableCell cellText = new TableCell();
				cellText.CssClass = "tweettext";
				HyperLink tweetLink = new HyperLink();
				tweetLink.CssClass = "tweet";
				tweetLink.NavigateUrl = "http://twitter.com/#!/" + o["from_user"].ToString();
				tweetLink.Text = tweet;
				tweetLink.Attributes.Add("rel", "nofollow");
				tweetLink.Target = "_blank";
				cellText.Controls.Add(tweetLink);

				row.Cells.Add(cellText);

				this.TweetTable.Rows.Add(row);

				colorIndex ^= 1;
			}
		}
	}
}